<template>
    <div id="operational">
      <!-- <p>立减活动</p>
      <hr>
      <br>
      <div class="el-alert el-alert--info"><i class="el-alert__icon el-icon-information is-big"></i>
        <div class="el-alert__content">
          <p class="el-alert__description">设置立减活动后，关联商品的价格会直接显示立减后的价格，并将常售价划掉，摆放在当前售价旁边。</p>
          </div>
      </div>
      <br> -->
      <p class="mt20">设置基本信息</p>
      <hr>
      <br>
      <div class="mt20">
        <el-row>
          <el-col :span='10'>
            <el-form :model="form" ref="form" :rules="rules" label-width="100px">
              <el-form-item label="活动主题" prop='name'>
                <el-input v-model="form.name"></el-input>
              </el-form-item>
              <el-form-item label="活动标签" prop='tag'>
                <el-input v-model="form.tag" :maxlength='6' placeholder='6个字以内'></el-input>
              </el-form-item>
              <el-form-item label="生效时间" prop='timeList'>
                <time-picker-group
                  :time-list = 'timeList'
                  type='campaignedit'
                  @updateTimeGroup = 'updateForm'
                ></time-picker-group>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
      <br>
      <p class="mt20">设置促销价格</p>
      <hr>
      <br>
      <div>
        <div>
          <el-button type="primary" icon="plus" @click='callPanel'>添加此活动关联的商品</el-button>
          <span>先选型所需关联的商品</span>
          </div>
      </div>
      <!-- 商品选择面板 -->
      <goods-select-panel
        ref='goodsSelectPanel'
        :prop-item = 'productList'
        @updateProduct = 'changeProductList'
      ></goods-select-panel>

      <!-- 设置价格策略面板 -->
      <strategy-price-table
        ref='strategyPriceTable'
        :productList = 'productList'
        :skuList ='skuList'
        :skuTableList = 'editParam.skuPriceList'
      ></strategy-price-table>
      <br>
      <p style="text-indent:400px">
        <el-button type="primary" size="large" @click='submitForm'>提交</el-button>
      </p>
      <activity-conflict-panel
        ref='activityConflictPanel'
      ></activity-conflict-panel>
    </div>
</template>
<script>
import goodsSelectPanel from 'components/operational/goodsSelectPanel.vue'
import timePickerGroup from 'components/operational/timePickerGroup.vue'
import strategyPriceTable from 'components/operational/strategyPriceTable.vue'
import activityConflictPanel from 'components/operational/activityConflictPanel.vue'
import {
  savePriceStrateg,
  getPriceStrategyById
} from 'src/api/index.js'
export default {
  beforeRouteEnter (to, from, next) {
    let query = to.query
    if (query.type && query.type === 'edit') {
      getPriceStrategyById({
        priceStrategyId: query.priceStrategyId || ''
      }).then((res) => {
        let result = res.data
        if (result.code === 100) {
          next((vm) => {
            vm.editParam = result.data
          })
        } else {
          window.alert(result.message)
          next()
        }
      })
    } else {
      next()
    }
  },
  created () {
    this.$route.meta.breadcrumbData = [
      {
        butRule: '/operational',
        name: '营销管理'
      },
      {
        butRule: '/operational/editLJCampaign',
        name: '编辑立减活动'
      }
    ]
  },
  mounted () {
    this.$nextTick(() => {
      this.setEditParam()
    })
  },
  data () {
    return {
      editParam: {},
      showPanel: false,
      timeList: [],
      productList: [],
      skuList: [],
      form: {
        name: '',
        tag: '',
        timeList: []
      },
      rules: {
        name: [
          {required: true, message: '请填写正确活动主题', trigger: 'blur'}
        ],
        tag: [
          {required: true, message: '请填写正确活动标签', trigger: 'blur'}
        ],
        timeList: [
          {
            required: true,
            validator: function (rule, value, callback) {
              if (value.length === 0) {
                callback(new Error('请设置有效生效时间'))
              }
              value.forEach((item) => {
                if (!item['effectBeginTime']) {
                  callback(new Error('请设置有效生效时间'))
                } else if (!item['effectEndTime']) {
                  callback(new Error('请设置有效生效时间'))
                }
              })
              callback()
            }
          }
        ]
      }
    }
  },
  watch: {
    'form.timeList': {
      deep: true,
      handler: function () {
        this.$refs.form.validateField('timeList')
      }
    }
  },
  methods: {
    setEditParam () {
      let editParam = this.editParam
      // 当为编辑时，填充默认参数
      if (editParam) {
        this.form.name = editParam.name
        this.form.tag = editParam.tag
        // 填充生效时间组
        editParam.timeList.forEach((item) => {
          let start = new Date(parseFloat(item.effectBeginTime))
          let end = new Date(parseFloat(item.effectEndTime))
          this.timeList.push({
            ...item,
            timePickerGroup: [start, end]
          })
        })
        // 设置productList，skuList
        editParam.skuPriceList.forEach((item) => {
          if (this.skuList.indexOf(item.skuId) === -1) {
            this.skuList.push(item.skuId)
          }
          if (this.productList.indexOf(item.productId) === -1) {
            this.productList.push(item.productId)
          }
        })
      }
    },
    callPanel () {
      this.$refs.goodsSelectPanel.showPanel()
    },
    changeProductList (productList) {
      this.productList = productList
    },
    updateForm (timeList) {
      // console.log(timeList)
      // return false
      this.form.timeList = timeList
    },
    submitForm () {
      let that = this
      this.validate()
        .then((validateResult) => {
          let param = that.editParam
          param['name'] = that.form.name
          param['tag'] = that.form.tag
          param['timeList'] = that.form.timeList
          param['skuPriceList'] = this.$refs.strategyPriceTable.getTableData()
          return savePriceStrateg(param)
        })
        .then((res) => {
          return new Promise((resolve, reject) => {
            let result = res.data
            if (result.code === 100) {
              if (result.data.failProductList && result.data.failProductList.length > 0) {
                // 出现商品冲突的情况
                resolve({
                  failProductList: result.data.failProductList,
                  cacheKey: result.data.cacheKey
                })
              } else {
                this.$alert('修改成功', {
                  confirmButtonText: '确定',
                  callback: action => {
                    this.$router.push({
                      path: '/operational/activitiesList'
                    })
                  }
                })
              }
            } else {
              this.$alert(result.message)
            }
          })
        })
        .then(this.handleConflict)
        .catch((result) => {
        })
    },
    validate () {
      return new Promise((resolve, reject) => {
        this.$refs.form.validate(function (result) {
          if (result) {
            resolve(result)
          } else {
            reject(result)
          }
        })
      })
    },
    handleConflict ({failProductList, cacheKey}) {
      // 处理冲突的情况
      this.$refs.activityConflictPanel.callPanel(failProductList, cacheKey)
    }
  },
  components: {
    goodsSelectPanel,
    timePickerGroup,
    strategyPriceTable,
    activityConflictPanel
  }
}
</script>
<style>
  #operational .el-alert__description {
    font-size:16px;
  }
</style>
